package com.concurrence;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

/**
 * ThreadPipeStream.. 两个线程之间流传输
 *
 * @author Lizhong
 * @date 2019/4/2
 */
public class ThreadPipeStream {
    public static void main(String[] args) throws IOException {
        PipedReader pipedReader = new PipedReader();
        PipedWriter pipedWriter = new PipedWriter();
        // 将reader与writer关联起来
        pipedWriter.connect(pipedReader);
        Thread thread = new Thread(new Runner(pipedReader));
        thread.start();
        int read = 0;
        try {
            while ((read = System.in.read()) != -1) {
                pipedWriter.write(read);
            }
        } catch (Exception e) {
            pipedWriter.close();
        }
    }

    static class Runner implements Runnable {
        PipedReader pipedReader;

        public Runner(PipedReader pipedReader) {
            this.pipedReader = pipedReader;
        }

        @Override
        public void run() {
            int read = 0;
            try {
                while ((read = pipedReader.read()) != -1) {
                    System.out.print((char) read);
                }
            } catch (Exception e) {

            }finally {
                try {
                    pipedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
